# encoding: UTF-8

class AuthenticationController < ApplicationController

  # Kiểm tra là user thì mới cho phép vào account_settings và set_account_info
  #before_filter :authenticate_user, :only => [:account_settings, :set_account_info]

  # Test OK
  def sign_in
    if current_user.nil?
      @user = NhanVien.new
    else
      redirect_to :root
    end
  end

  # ========= Signing In ==========
  # Test OK
  def login
    username_or_email = params[:user][:MaNV]
    user = verify_user(username_or_email)

    if user
      update_authentication_token(user, params[:user][:remember_me])
      user.last_signed_in_on=DateTime.now
      puts user.save
      session[:user_id] = user.id
      flash[:notice] = 'Bạn đã đăng nhập thành công!'
      redirect_to :root
    else
      flash.now[:error] = 'Mã nhân viên(email) hoặc mật khẩu bạn đã nhập không chính xác.'
      render :action => "sign_in"

    end
  end

  # ========= Signing Out ==========
  # Test OK
  def signed_out
    # clear the authentication toke when the user manually signs out
    user = current_user
    #user ||= NhanVien.find_by_id(session[:user_id])
    #user ||= NhanVien.find_by_authentication_token(cookies[:auth_token])

    if user
      update_authentication_token(user, nil)
      user.save
      session[:user_id] = nil
      flash[:notice] = "Bạn đã đăng xuất thành công!"
      redirect_to :root
    else
      redirect_to :root
    end
  end

  # ========= Handles Registering a New User ==========
  # Test OK
  def new_user
    #Rails.logger.warn current_user.MaCV_id.class
    #Rails.logger.warn '-'*80

    if !current_user.nil? && current_user.MaNV == 1 && current_user.MaCV_id == 1
      @user = NhanVien.new
    else
      flash[:notice] = 'Bạn không có quyền đăng kí thành viên mới!'
      redirect_to :root
    end
  end

  # Test OK
  def register
    @user = NhanVien.new(params[:user])

    # Don't use !verify_recaptcha, as this terminates the connection with the server.
    # It almost seems as if the verify_recaptcha is being called twice with we use "not".
    #if verify_recaptcha

      if @user.valid?
        update_authentication_token(@user,params[:user][:remember_me])  #nil)
        @user.signed_up_on = DateTime.now
        @user.last_signed_in_on = @user.signed_up_on
        @user.save
        UserMailer.welcome_email(@user).deliver
        #session[:user_id] = @user.id
        #flash[:notice] = 'Welcome.'
        redirect_to :root
      else
        render :action => "new_user"
      end

    #else
    #  flash.delete(:recaptcha_error)  # get rid of the recaptcha error being flashed by the gem.
    #  flash.now[:error] = 'reCAPTCHA is incorrect.  Please try again.'
    #  render :action => "new_user"
    #end
  end

  # ========= Handles Changing Account Settings ==========

  # Test OK, còn đổi pass và email
  def account_settings
    @user = current_user
  end

  def set_account_info
    old_user = current_user

    # verify the current password by creating a new user record.
    @user = NhanVien.authenticate_by_username(old_user.MaNV, params[:user][:password])

    puts @user

    # verify
    if @user.nil?
      @user = old_user
      @user.errors[:password] = "Mật khẩu không đúng."
      render :action => "account_settings"
    else
      # update the user with any new username and email
      @user.update(params[:user])
      # Set the old email and username, which is validated only if it has changed.
      @user.previous_email = old_user.Email

      if @user.valid?
        # If there is a new_password value, then we need to update the password.
        @user.password = @user.new_password unless @user.new_password.nil? || @user.new_password.empty?
        @user.save
        flash[:notice] = 'Thông tin tài khoản của bạn đã thay đổi thành công!'
        #redirect_to :root
        render :action => "account_settings"
      else
        @user.Email = old_user.Email
        render :action => "account_settings"
      end
    end
  end

  # ========= Handles Password Reset ==========

  # HTTP get
  # Test OK
  def forgot_password
    @user = NhanVien.new
  end

  # HTTP put
  # Test OK
  def send_password_reset_instructions
    username_or_email = params[:user][:MaNV]

    if username_or_email.to_s.rindex('@')
      user = NhanVien.find_by_Email(username_or_email)
    else
      user = NhanVien.find_by_MaNV(username_or_email)
    end

    if user
      user.password_reset_token = SecureRandom.urlsafe_base64
      user.password_expires_after = 1.minutes.from_now
      user.save
      UserMailer.reset_password_email(user).deliver
      flash[:notice] = 'Một lá thư hướng dẫn khôi phục mật khẩu đã được gửi đến hòm thư của bạn! Hãy kiểm tra!'
      redirect_to :sign_in
    else
      @user = NhanVien.new
      # put the previous value back.
      @user.MaNV = params[:user][:MaNV]
      @user.errors[:MaNV] = 'Xin lỗi! Dữ liệu bạn đưa không có trong CSDL!'
      render :action => "forgot_password"
    end
  end

  # The user has landed on the password reset page, they need to enter a new password.
  # HTTP get
  # Test OK
  def password_reset
    token = params.first[0]
    @user = NhanVien.find_by_password_reset_token(token)

    if @user.nil?
      flash[:error] = 'Bạn không có yêu cầu khôi phục mật khẩu.'
      redirect_to :root
      return
    end

    if @user.password_expires_after < DateTime.now
      clear_password_reset(@user)
      @user.save
      flash[:error] = 'Đường dẫn khôi phục mật khẩu đã quá hạn. Bạn vui lòng gửi lại yêu cầu khôi phục mật khẩu mới.'
      redirect_to :forgot_password
    end
  end

  # The user has entered a new password.  Need to verify and save.
  # HTTP put
  # Test OK
  def new_password
    username = params[:user][:MaNV]
    @user = NhanVien.find_by_MaNV(username)

    if verify_new_password(params[:user])
      puts params.inspect
      @user.update(params[:user])
      #@user.new_password = params[:user][:new_password]
      #@user.new_password_confirmation = params[:user][:new_password_confirmation]

      @user.password = @user.new_password

      if @user.valid?
        clear_password_reset(@user)
        @user.save
        flash[:notice] = 'Mật khẩu của bạn đã khôi phục thành công. Bạn hãy đăng nhập với mật khẩu mới.'
        redirect_to :sign_in
      else
        render :action => "password_reset"
      end
    else
      @user.errors[:new_password] = 'Mật khẩu không được trống và phải khớp với nhắc lại mật khẩu.'
      render :action => "password_reset"
    end
  end

  # ========= Private Functions ==========

  private

  # Test OK
  def clear_password_reset(user)
    user.password_expires_after = nil
    user.password_reset_token = nil
  end

  # Test OK
  def verify_new_password(passwords)
    result = true
    if passwords[:new_password].blank? || (passwords[:new_password] != passwords[:new_password_confirmation])
      result=false
    end
    result
  end

  # Verifies the user by checking their email and password or their username and password
  # Test OK
  def verify_user(username_or_email)
    password = params[:user][:password]
    if username_or_email.to_s.rindex('@')
      puts "email"
      email=username_or_email
      user = NhanVien.authenticate_by_email(email, password)
    else
      puts "username"
      username=username_or_email
      user = NhanVien.authenticate_by_username(username, password)
    end
    user
  end

  # Test OK
  def update_authentication_token(user, remember_me)
    if remember_me == "1"
      # create an authentication token if the user has clicked on remember me
      auth_token = SecureRandom.urlsafe_base64
      user.authentication_token = auth_token
      cookies.permanent[:auth_token] = auth_token
    else              # nil or 0
                      # if not, clear the token, as the user doesn't want to be remembered.
      user.authentication_token = nil
      cookies.permanent[:auth_token] = nil
    end
  end
end
